<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-delete" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseModelList">
      <el-table-column width="55" align="center" />
      <el-table-column label="房型名称" align="center" prop="attrName" />
      <el-table-column label="房间总数" align="center" prop="roomNum" />
      <el-table-column label="价格" align="center" prop="price" />
      <!-- <el-table-column label="创建日期" align="center" prop="createTime" /> -->
      <el-table-column prop="isDel" label="是否删除" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="房型名称" prop="attrName">
              <el-input v-model="form.attrName" placeholder="请输入房型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间总数" prop="roomNum">
              <el-input v-model="form.roomNum" placeholder="请输入房间总数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入房间总数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属酒店" prop="hotelId">
              <el-select v-model="form.hotelId" placeholder="请选择酒店">
                <el-option v-for="item in hotelList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="轮播图片" prop="indexImg" label-width="80px">
              <el-upload class="avatar-uploader" :action="uploadImgUrl" list-type="picture-card" :multiple="true"
                :limit="5" :file-list="fileList" :on-exceed="handleExceed" :on-success="handleSuccess"
                :on-remove="handleRemove" :before-upload="beforeUpload" accept="image/jpeg,image/png">
                <!-- 自定义上传按钮 -->
                <template #trigger>
                  <div v-if="!isLimitReached" class="upload-btn">
                    <i class="el-icon-plus"></i>
                  </div>
                </template></el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getHouseModelList, AddHouseModel, UpdateHouseModel, DelHouseModel, GetDetail } from "@/api/houseModel";
import { getHotelList } from '@/api/hotel'
import { uploadImage } from "@/api/hotel";
import { UpdateHotel } from "../../api/hotel";
export default {
  name: "Hotel",
  data () {
    return {
      title: '',
      // 遮罩层
      loading: true,
      open: false,
      uploadImgUrl: "https://admin.gzh.wowotou.online/system/upload/image",
      // 选中数组
      uploadImgDisabled: '',
      ids: [],
      fileList: [],
      form: {},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房型数据
      houseModelList: [],
      //酒店下拉列表
      hotelList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      hotelParams: {
        pageNum: 1,
        pageSize: 999
      },
      imageUrl: "",
      rules: {
        attrName: [
          { required: true, message: "酒店名称不能为空", trigger: "blur" }
        ],
        roomNum: [
          { required: true, message: "房间总数不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created () {
    this.getList();
   
  },
  computed: {
    isLimitReached () {
      return this.fileList.length >= 5
    }
  },
  methods: {
    beforeUpload (file) {
      const isImage = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传 JPG/PNG 格式的图片!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }

      return isImage && isLt2M;
    },
    // 上传成功回调
    handleSuccess (response, file, fileList) {
      this.fileList = fileList;
      this.$message.success('上传成功');

      // 这里可以处理返回的图片地址
      console.log('上传成功响应:', response);
    },

    // 移除文件回调
    handleRemove (file, fileList) {
      this.fileList = fileList;
      this.$message.warning('已移除图片');

      // 这里可以调用API删除服务器文件
      console.log('需要删除的文件:', file);
    },

    // 超过限制时的处理
    handleExceed (files, fileList) {
      this.$message.warning(`最多上传5张图片，当前已选择 ${files.length} 张`);
    },
    getHotelList () {
      getHotelList(this.hotelParams).then((response) => {
        this.hotelList = response.data.list.map(item => ({
          label: item.hotelName,  // 对应原始数据的 hotelName
          value: item.id          // 对应原始数据的 id
        }));
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids;
      this.getHotelList()
      GetDetail(id).then((response) => {
        this.form = response.data
        this.open = true;
        this.title = "修改房型信息";
      });
    },
    async handleUploadForm (param) {
      console.log(param)
      const formData = new FormData();
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      formData.append("file", param.file);
      try {
        const res = await uploadImage(formData, Math.floor(Math.random() * 10));
        this.Imgs.push({
          name: res.data.fileName,
          url: res.data.url
        });

        this.form.imgs = this.Imgs;
        loading.close();
      } catch (e) {
        console.log(e)
        loading.close();
      }
    },
    handleAdd (row) {
      this.reset();
      this.open = true;
      this.title = "添加房型";
      this.getHotelList()
    },
    /** 查询用户列表 */
    getList () {
      this.loading = true;
      getHouseModelList(this.queryParams).then((response) => {
        this.houseModelList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => {
        return item.id;
      });
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除房型信息？")
        .then(function () {
          return DelHouseModel(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 提交按钮 */
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.images = this.fileList.map(a=>{
            a.url
          })
          if (this.form.id != null) {
            UpdateHouseModel(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            AddHouseModel(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        hotelId: undefined,
        images: undefined,
        attrName: undefined,
        roomNum: undefined,
        price: undefined
      };
      this.fileList =[]
      this.resetForm("form");
    },
  },
};
</script>
<style scoped lang="scss">
.modal-wrap {
  ::v-deep .el-dialog__body {
    height: 600px;
    overflow-y: scroll;
  }
}

.avatar-uploader {
  ::v-deep .el-upload {
    width: 100px;
    height: 100px;
    border: 1px dotted #eee;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar-uploader-icon {
    font-size: 24px;
  }
}

.banner-img {
  width: 80px;
  height: 80px;
  // margin-left: 20px;
}

.editBox {
  display: flex;
  justify-content: space-between;
}

.custom-upload {
  ::v-deep .el-upload {
    // 隐藏默认上传按钮
    display: none;
  }

  // 图片项样式
  .image-item {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
    margin-right: 10px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;

    .el-image {
      width: 100%;
      height: 100%;
    }

    .el-icon-close {
      position: absolute;
      right: -8px;
      top: -8px;
      cursor: pointer;
      background: #fff;
      border-radius: 50%;
    }
  }

  // 自定义上传按钮
  .upload-btn {
    display: inline-flex;
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }
  }

  // 隐藏达到限制时的按钮
  .hide-add-btn .upload-btn {
    display: none;
  }
}
</style>
